package jdk5.concurrent.tiger;

import java.util.concurrent.Semaphore;

import jdk5.common.Teacher;

public class School{
       private static final int NO_TEACHER = 5;
       private static final Semaphore available = new Semaphore(NO_TEACHER, true);

       private Teacher[] teachers = new Teacher[]{
                  new Teacher("George"), 
                  new Teacher("Alan"),
                  new Teacher("Dirk"),
                  new Teacher("Hiloo"),
                  new Teacher("Haige")
       };

        public Teacher go2Class() throws InterruptedException{
                available.acquire();
                return getAvailableTeacher();
       }

       public void  dismissClass(Teacher teacher) {
             if(markAsRest(teacher))
                   available.release();
       }
  
      synchronized private Teacher getAvailableTeacher(){
             for(int i = 0; i < NO_TEACHER; i++){
                      if(!teachers[i].isBusy()){
		teachers[i].teach();
                                      return teachers[i];
                      }
                }
              return null;
      }

      synchronized private boolean markAsRest(Teacher teacher){
	for(int i = 0; i < NO_TEACHER; i++){
                            if(teacher ==  teachers[i]){
                                  if(teacher.isBusy()){
                                               teacher.rest();
                                               return true;
                                  } else return false;
                             } 
                  }
                  return false;
     }      
}